#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能算法优化库演示

本示例展示如何使用智能算法库进行优化问题求解，包括：
1. 基本优化问题求解
2. 算法性能基准测试
3. 标准测试函数优化
4. 算法信息查询
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.models import (
    DecisionVariable, ObjectiveFunction, OptimizationProblem,
    VariableType, OptimizationType
)
from src.intelligent_algorithm_library import IntelligentAlgorithmLibrary, AlgorithmParameters
import math
import time

def demo_basic_optimization():
    """演示基本优化问题求解"""
    print("=" * 50)
    print("演示1: 基本优化问题求解")
    print("=" * 50)
    
    # 创建智能算法库实例
    library = IntelligentAlgorithmLibrary()
    
    # 创建一个简单的二次函数优化问题: minimize f(x,y) = (x-2)^2 + (y-3)^2
    variables = [
        DecisionVariable(
            name="x",
            variable_type=VariableType.CONTINUOUS,
            lower_bound=-10,
            upper_bound=10,
            description="决策变量x"
        ),
        DecisionVariable(
            name="y",
            variable_type=VariableType.CONTINUOUS,
            lower_bound=-10,
            upper_bound=10,
            description="决策变量y"
        )
    ]
    
    objective = ObjectiveFunction(
        name="quadratic_function",
        optimization_type=OptimizationType.MINIMIZE,
        expression="(x-2)**2 + (y-3)**2",
        description="二次函数优化"
    )
    
    problem = OptimizationProblem(
        name="quadratic_optimization",
        variables=variables,
        objectives=[objective],
        description="简单二次函数优化问题"
    )
    
    # 定义目标函数
    def objective_function(solution):
        x, y = solution[0], solution[1]
        return -((x-2)**2 + (y-3)**2)  # 负号因为算法库期望最大化
    
    # 使用自适应遗传算法求解
    print("\n使用自适应遗传算法求解...")
    parameters = AlgorithmParameters(
        population_size=30,
        max_iterations=50,
        crossover_rate=0.8,
        mutation_rate=0.1
    )
    
    result = library.optimize_problem(
        problem=problem,
        algorithm_name="adaptive_ga",
        objective_function=objective_function,
        parameters=parameters
    )
    
    print(f"\n优化结果:")
    print(f"目标函数值: {-result.objective_value:.6f}")  # 还原真实值
    print(f"执行时间: {result.execution_time:.2f}秒")
    print(f"迭代次数: {result.iterations}")
    # 获取解的键名
    solution_keys = list(result.solution.keys())
    if len(solution_keys) >= 2:
        x_val = result.solution[solution_keys[0]]
        y_val = result.solution[solution_keys[1]]
        print(f"最优解: x={x_val:.6f}, y={y_val:.6f}")
        print(f"理论最优解: x=2.0, y=3.0")
        print(f"误差: x误差={abs(x_val-2):.6f}, y误差={abs(y_val-3):.6f}")
    else:
        print(f"最优解: {result.solution}")
        print(f"理论最优解: x=2.0, y=3.0")

def demo_algorithm_benchmark():
    """演示算法性能基准测试"""
    print("\n" + "=" * 50)
    print("演示2: 算法性能基准测试")
    print("=" * 50)
    
    library = IntelligentAlgorithmLibrary()
    
    # 创建Rosenbrock函数优化问题
    variables = [
        DecisionVariable(
            name=f"x{i}",
            variable_type=VariableType.CONTINUOUS,
            lower_bound=-2.048,
            upper_bound=2.048,
            description=f"决策变量x{i}"
        ) for i in range(5)  # 5维Rosenbrock函数
    ]
    
    objective = ObjectiveFunction(
        name="rosenbrock_function",
        optimization_type=OptimizationType.MINIMIZE,
        description="Rosenbrock函数优化"
    )
    
    problem = OptimizationProblem(
        name="rosenbrock_optimization",
        variables=variables,
        objectives=[objective],
        description="5维Rosenbrock函数优化问题"
    )
    
    # 定义Rosenbrock函数
    def rosenbrock_function(x):
        result = 0
        for i in range(len(x) - 1):
            result += 100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2
        return -result  # 负号因为算法库期望最大化
    
    # 进行基准测试
    print("\n进行算法基准测试...")
    algorithms = ["adaptive_ga", "hybrid_pso_sa", "differential_evolution"]
    
    benchmark_results = library.benchmark_algorithms(
        problem=problem,
        objective_function=rosenbrock_function,
        algorithms=algorithms,
        runs=3  # 每个算法运行3次
    )
    
    # 显示结果
    print("\n基准测试结果:")
    for algo_name, metrics in benchmark_results.items():
        print(f"\n{algo_name}:")
        print(f"  平均适应度: {-metrics['mean_fitness']:.6f}")  # 还原真实值
        print(f"  标准差: {metrics['std_fitness']:.6f}")
        print(f"  最佳适应度: {-metrics['best_fitness']:.6f}")
        print(f"  平均时间: {metrics['mean_time']:.3f}秒")
    
    # 算法排名
    ranking = sorted(
        benchmark_results.items(),
        key=lambda x: x[1]['mean_fitness'],
        reverse=True  # 因为我们取了负号，所以reverse=True表示最小化
    )
    
    print("\n算法排名:")
    for i, (algo_name, metrics) in enumerate(ranking, 1):
        print(f"{i}. {algo_name} (平均适应度: {-metrics['mean_fitness']:.6f})")

def demo_test_functions():
    """演示标准测试函数优化"""
    print("\n" + "=" * 50)
    print("演示3: 标准测试函数优化")
    print("=" * 50)
    
    library = IntelligentAlgorithmLibrary()
    
    # 测试不同的标准函数
    test_functions = {
        "sphere": {
            "func": lambda x: sum(xi**2 for xi in x),
            "bounds": (-5.12, 5.12),
            "optimal": 0,
            "description": "球面函数"
        },
        "rastrigin": {
            "func": lambda x: 10*len(x) + sum(xi**2 - 10*math.cos(2*math.pi*xi) for xi in x),
            "bounds": (-5.12, 5.12),
            "optimal": 0,
            "description": "Rastrigin函数"
        },
        "ackley": {
            "func": lambda x: 20 + math.e - 20*math.exp(-0.2*math.sqrt(sum(xi**2 for xi in x)/len(x))) - math.exp(sum(math.cos(2*math.pi*xi) for xi in x)/len(x)),
            "bounds": (-32.768, 32.768),
            "optimal": 0,
            "description": "Ackley函数"
        }
    }
    
    dimension = 10
    
    for func_name, func_info in test_functions.items():
        print(f"\n测试函数: {func_info['description']}")
        print("-" * 30)
        
        # 创建问题
        variables = [
            DecisionVariable(
                name=f"x{i}",
                variable_type=VariableType.CONTINUOUS,
                lower_bound=func_info["bounds"][0],
                upper_bound=func_info["bounds"][1],
                description=f"决策变量x{i}"
            ) for i in range(dimension)
        ]
        
        objective = ObjectiveFunction(
            name=f"{func_name}_function",
            optimization_type=OptimizationType.MINIMIZE,
            description=func_info["description"]
        )
        
        problem = OptimizationProblem(
            name=f"{func_name}_optimization",
            variables=variables,
            objectives=[objective],
            description=f"{dimension}维{func_info['description']}优化问题"
        )
        
        # 定义目标函数（转换为最大化）
        objective_function = lambda x: -func_info["func"](x)
        
        # 使用自适应遗传算法求解
        parameters = AlgorithmParameters(
            population_size=50,
            max_iterations=100
        )
        
        result = library.optimize_problem(
            problem=problem,
            algorithm_name="adaptive_ga",
            objective_function=objective_function,
            parameters=parameters
        )
        
        actual_value = -result.objective_value  # 还原真实值
        error = abs(actual_value - func_info["optimal"])
        
        print(f"目标函数值: {actual_value:.6f}")
        print(f"理论最优值: {func_info['optimal']}")
        print(f"误差: {error:.6f}")
        print(f"执行时间: {result.execution_time:.2f}秒")

def demo_algorithm_info():
    """演示算法信息查询"""
    print("\n" + "=" * 50)
    print("演示4: 算法信息查询")
    print("=" * 50)
    
    library = IntelligentAlgorithmLibrary()
    
    # 获取可用算法列表
    algorithms = library.get_available_algorithms()
    print(f"\n可用算法: {', '.join(algorithms)}")
    
    # 获取每个算法的详细信息
    for algo_name in algorithms:
        print(f"\n{'-' * 40}")
        info = library.get_algorithm_info(algo_name)
        print(f"算法: {info['name']}")
        print(f"描述: {info['description']}")
        print("主要参数:")
        for param in info['parameters']:
            print(f"  - {param}")
        print("适用场景:")
        for scenario in info['suitable_for']:
            print(f"  - {scenario}")

def main():
    """主函数"""
    print("智能算法优化库演示")
    print("=" * 60)
    
    try:
        # 演示1: 基本优化问题求解
        demo_basic_optimization()
        
        # 演示2: 算法性能基准测试
        demo_algorithm_benchmark()
        
        # 演示3: 标准测试函数优化
        demo_test_functions()
        
        # 演示4: 算法信息查询
        demo_algorithm_info()
        
        print("\n" + "=" * 60)
        print("演示完成！")
        
    except Exception as e:
        print(f"\n演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()